package com.nofeng.wx.third;


import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nofeng.wx.utils.NoHttpsClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class BaiduAiApi {

    public static final String API_KEY = "7BE8TmM3Cm1BX6HZm6PbsUpI";
    public static final String SECRET_KEY = "SYMoD2aU3SbQWHsbVnKZNNbAR6wIW1zc";


    public String getAccessToken() throws Exception {
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
        HttpEntity<String> entity = new HttpEntity<>(headers);

        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=" + API_KEY + "&client_secret=" + SECRET_KEY;
        String resp = restTemplate.postForObject(url, entity, String.class);
        return JSONObject.parseObject(resp).getString("access_token");
    }


    public String ask(List<String> messages) throws Exception {
        RestTemplate restTemplate = NoHttpsClientUtils.getRestTemplate(30000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
        Map<String, List<Map<String, String>>> body = Maps.newHashMap();
        List<Map<String, String>> reqMessages = Lists.newArrayList();
        for (String message : messages) {
            Map<String, String> m = Maps.newHashMap();
            m.put("role", "user");
            m.put("content", message);
            reqMessages.add(m);
        }
        body.put("messages", reqMessages);
        HttpEntity entity = new HttpEntity<>(JSONObject.toJSONString(body), headers);
        String accessToken = getAccessToken();
        String url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/eb-instant?access_token=" + accessToken;
        try {
            String resp = restTemplate.postForObject(url, entity, String.class);
            return StringUtils.defaultIfEmpty(JSONObject.parseObject(resp).getString("result"), "我还不懂");
        } catch (Exception e) {
            return "超时";
        }
    }

    public String ask(String messages) throws Exception {
        return ask(Lists.newArrayList(messages));
    }
}
